//
//  UIImage+Extended.m
//  Game
//
//  Created by apple on 13-6-10.
//  Copyright (c) 2013年 apple. All rights reserved.
//

#import "UIImage+Extended.h"
#import <QuartzCore/QuartzCore.h>
#import <Accelerate/Accelerate.h>

@implementation UIImage (Extended)

+(UIImage *)createUIImageWithSize:(CGSize)imageSize imageColor:(UIColor *)imageColor
{
    UIGraphicsBeginImageContextWithOptions(imageSize, 0, [UIScreen mainScreen].scale);
    [imageColor set];
    UIRectFill(CGRectMake(0, 0, imageSize.width, imageSize.height));
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

// 将UIImage缩放到指定大小尺寸：
- (UIImage *)scaleToSize:(CGSize)newsize{
    
    if (newsize.height<0.1||newsize.width<0.1) {
        return self;
    }
    if (self.size.width>self.size.height) {
        newsize=CGSizeMake(newsize.height, newsize.width);
    }
    //取最小值
    float scale=MIN(newsize.width/self.size.width, newsize.height/self.size.height);
    if (scale>=1) {
        return self;
    }
    // 把它设置成为当前正在使用的context
    UIGraphicsBeginImageContextWithOptions(newsize, NO, 1.0);
    UIGraphicsBeginImageContext(newsize);
    CGRect theRect=CGRectMake(0, 0, self.size.width*scale, self.size.height*scale);
    // 绘制改变大小的图片
    [self drawInRect:theRect];
    
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef theImg=CGImageCreateWithImageInRect(scaledImage.CGImage, theRect);
    // 返回新的改变大小后的图片
    UIImage*getImg=[UIImage imageWithCGImage:theImg];
    CGImageRelease(theImg);
    return getImg;
}

-(UIImage *)scaleToSizeBig:(CGSize)size {
    CGFloat width = size.width, height = size.height;
    CGFloat imgDiv = self.size.width/self.size.height;
    if (imgDiv > 1) {
        width = size.height;
        height = size.width;
    }
    CGFloat frameDiv = size.width/size.height;
    if(imgDiv > frameDiv) {
        if (height>self.size.height) {
            return self;
        }
        width = height*imgDiv;
    } else if(imgDiv < frameDiv) {
        if (width>self.size.width) {
            return self;
        }
        height = width/imgDiv;
    }
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    // 绘制改变大小的图片
    [self drawInRect:CGRectMake(0, 0, width, height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}


-(UIImage *)getSubImage:(CGRect)rect
{
    CGFloat scale=[self scale];
    UIImage *reVal=nil;
    // 起点在图片外，直接返回nil
    if (rect.origin.x>self.size.width-1||rect.origin.y>self.size.height-1) {
        return reVal;
    }
    // 图片的宽度超出限制的处理
    if (rect.origin.x+rect.size.width>self.size.width) {
        rect.size.width=self.size.width-rect.origin.x;
    }
    // 图片的高度超出限制的处理
    if (rect.origin.y+rect.size.height>self.size.height) {
        rect.size.height=self.size.height-rect.origin.y;
    }
    
    rect.origin.x*=scale;
    rect.origin.y*=scale;
    rect.size.width*=scale;
    rect.size.height*=scale;
    CGImageRef imageRef=self.CGImage;
    CGImageRef subImageRef=CGImageCreateWithImageInRect(imageRef, rect);
    CGSize size=CGSizeMake(rect.size.width, rect.size.height);
    
    UIGraphicsBeginImageContextWithOptions(size, NO, scale);
    CGContextRef context=UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, rect, subImageRef);

    reVal=[UIImage imageWithCGImage:subImageRef scale:scale orientation:UIImageOrientationUp];
    CGImageRelease(subImageRef);
    UIGraphicsEndImageContext();
    return reVal;
}
 
-(UIImage *)mergeImage:(UIImage *)backgroundImgae point:(CGPoint)point frontImage:(UIImage *)frontImage
{
    UIImage *reVal=nil;
    UIGraphicsBeginImageContext([backgroundImgae size]);
    [backgroundImgae drawAtPoint:CGPointMake(0,0)];
    [frontImage drawAtPoint:CGPointMake(0,0)];
    reVal = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return reVal;
}

-(UIImage *)mergeImageWithPoint:(CGPoint)point image:(UIImage *)image
{
    UIImage *reVal=nil;
    if ([self scale]!=[image scale]) {
        reVal=nil;
        return reVal;
    }
    UIGraphicsBeginImageContextWithOptions([self size], NO, [self scale]);
    [self drawAtPoint:CGPointMake(0, 0)];
    [image drawAtPoint:point];
    reVal = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return reVal;
}

-(UIImage *)mergeImageWithFrame:(CGRect)frame image:(UIImage *)image
{
    if ([image size].width!=frame.size.width||[image size].height!=frame.size.height) {
        image=[image scaleToSize:frame.size];
    }
    UIImage *reVal=[self mergeImageWithPoint:frame.origin image:image];
    return reVal;
}

+(UIImage *)Superposition:(UIImage *)image withInsets:(UIEdgeInsets)insets andShadowImage:(UIImage *)shadowImage
{
    CGSize size=image.size;
    if (size.width<shadowImage.size.width) {
        size.width=shadowImage.size.width;
    }
    if (size.height<shadowImage.size.height) {
        size.height=shadowImage.size.height;
    }
    if (!CGSizeEqualToSize(image.size,size)) {
        image=[image scaleToSize:size];
    }
    if (!CGSizeEqualToSize(shadowImage.size,size)) {
        shadowImage=[shadowImage scaleToSize:size];
    }
    image=[image mergeImageWithPoint:CGPointMake(0, 0) image:shadowImage];
    image=[image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    return image;
}

+(UIImage *)imageFromLabel:(UILabel *)label
{
    UIImage *image=[self createUIImageWithSize:label.frame.size imageColor:[UIColor clearColor]];
    image=[image mergeImageWithLabel:label inRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    return image;
}

-(UIImage *)mergeImageWithLabel:(UILabel *)label inRect:(CGRect)rect
{
    UIImage *reVal=nil;
//    UIGraphicsBeginImageContext([self size]);
    UIGraphicsBeginImageContextWithOptions([self size], NO, [self scale]);
    [self drawAtPoint:CGPointMake(0, 0)];
    [label drawTextInRect:rect];
//    [label.layer renderInContext:UIGraphicsGetCurrentContext()];
    reVal = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return reVal;
}

-(UIImage *)mergeImageWithText:(NSString *)text color:(UIColor *)color font:(UIFont *)font inRect:(CGRect)rect
{
    UIImage *reVal=nil;
    UIGraphicsBeginImageContextWithOptions([self size], NO, [self scale]);
    [self drawAtPoint:CGPointMake(0, 0)];
    NSInteger argbColor=[self ARGBFromUIColor:color];
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), ((argbColor>>16)&0xff)/255.0f, ((argbColor>>8)&0xff)/255.0f, ((argbColor)&0xff)/255.0f, ((argbColor>>24)&0xff)/255.0f);
    [text drawAtPoint:rect.origin withFont:font];
    reVal = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"Draw Ok2");
    return reVal;
}

-(NSInteger)ARGBFromUIColor:(UIColor *)color
{
    NSInteger argb=0;
    NSString *rgbString=[NSString stringWithFormat:@"%@",color];
    NSArray *rgbArray=[rgbString componentsSeparatedByString:@" "];
    NSInteger r=round([[rgbArray objectAtIndex:1] integerValue]*255);
    NSInteger g=round([[rgbArray objectAtIndex:2] integerValue]*255);
    NSInteger b=round([[rgbArray objectAtIndex:3] integerValue]*255);
    NSInteger a=round([[rgbArray objectAtIndex:4] integerValue]*255);
    argb=((a*256+r)*256+g)*256+b;
    return argb;
}

-(UIImage *)mergeImageWithSize:(CGSize)size point1:(CGPoint)point1 image1:(UIImage *)image1 point2:(CGPoint)point2 image2:(UIImage *)image2
{
    UIImage *reVal=nil;
    if ([image1 scale]!=[image2 scale]) {
        reVal=nil;
        return reVal;
    }
    UIGraphicsBeginImageContextWithOptions(size, NO, [image1 scale]);
    [image1 drawAtPoint:point1];
    [image2 drawAtPoint:point2];
    reVal = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return reVal;
}

-(UIImage *)mergeImageWithSize:(CGSize)size frame1:(CGRect)frame1 image1:(UIImage *)image1 frame2:(CGRect)frame2 image2:(UIImage *)image2
{
    if ([image1 size].width!=frame1.size.width||[image1 size].height!=frame1.size.height) {
        image1=[image1 scaleToSize:frame1.size];
    }
    if ([image2 size].width!=frame2.size.width||[image2 size].height!=frame2.size.height) {
        image2=[image2 scaleToSize:frame2.size];
    }
    UIImage *reVal=[self mergeImageWithSize:size point1:frame1.origin image1:image1 point2:frame2.origin image2:image2];
    return reVal;
}

-(UIImage *)createUIImageWithSize:(CGSize)imageSize color:(UIColor *)color
{
    UIGraphicsBeginImageContextWithOptions(imageSize, 0, [UIScreen mainScreen].scale);
    [color set];
    UIRectFill(CGRectMake(0, 0, imageSize.width, imageSize.height));
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


-(UIImage *)setImage:(UIImage *)image inset:(UIEdgeInsets) insets
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0) {
        image=[image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    }else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0) {
        image=[image resizableImageWithCapInsets:insets];
    }else if([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0) {
        image=[image stretchableImageWithLeftCapWidth:insets.left topCapHeight:insets.top];
    }
    return image;
}

+(UIImage*)ImageWithUIcolor:(UIColor*)color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

- (UIImage *)bundleImageName:(NSString *)imageName {
	NSString *path = [[NSBundle mainBundle] pathForResource:[imageName stringByDeletingPathExtension] ofType:[imageName pathExtension]];
	UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];
	
	return image ;
}

- (UIImage *)fixOrientation {
    
    // No-op if the orientation is already correct
    if (self.imageOrientation == UIImageOrientationUp) return self;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (self.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, self.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    
    switch (self.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, self.size.width, self.size.height,
                                             CGImageGetBitsPerComponent(self.CGImage), 0,
                                             CGImageGetColorSpace(self.CGImage),
                                             CGImageGetBitmapInfo(self.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (self.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (UIImage *)crop:(CGRect)rect {
    
    rect = CGRectMake(rect.origin.x * self.scale,
                      rect.origin.y * self.scale,
                      rect.size.width * self.scale,
                      rect.size.height * self.scale);
    
    CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

-(UIImage*)resizedImageToSize:(CGSize)dstSize
{
    CGImageRef imgRef = self.CGImage;
    // the below values are regardless of orientation : for UIImages from Camera, width>height (landscape)
    CGSize  srcSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef)); // not equivalent to self.size (which is dependant on the imageOrientation)!
    
    /* Don't resize if we already meet the required destination size. */
    if (CGSizeEqualToSize(srcSize, dstSize)) {
        return self;
    }
    
    CGFloat scaleRatio = dstSize.width / srcSize.width;
    UIImageOrientation orient = self.imageOrientation;
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch(orient) {
            
        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;
            
        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(srcSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;
            
        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(srcSize.width, srcSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, srcSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;
            
        case UIImageOrientationLeftMirrored: //EXIF = 5
            dstSize = CGSizeMake(dstSize.height, dstSize.width);
            transform = CGAffineTransformMakeTranslation(srcSize.height, srcSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI_2);
            break;
            
        case UIImageOrientationLeft: //EXIF = 6
            dstSize = CGSizeMake(dstSize.height, dstSize.width);
            transform = CGAffineTransformMakeTranslation(0.0, srcSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI_2);
            break;
            
        case UIImageOrientationRightMirrored: //EXIF = 7
            dstSize = CGSizeMake(dstSize.height, dstSize.width);
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight: //EXIF = 8
            dstSize = CGSizeMake(dstSize.height, dstSize.width);
            transform = CGAffineTransformMakeTranslation(srcSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
            
    }
    
    /////////////////////////////////////////////////////////////////////////////
    // The actual resize: draw the image on a new context, applying a transform matrix
    UIGraphicsBeginImageContextWithOptions(dstSize, NO, self.scale);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    if (!context) {
        return nil;
    }
    
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -srcSize.height, 0);
    } else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -srcSize.height);
    }
    
    CGContextConcatCTM(context, transform);
    
    // we use srcSize (and not dstSize) as the size to specify is in user space (and we use the CTM to apply a scaleRatio)
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, srcSize.width, srcSize.height), imgRef);
    UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resizedImage;
}



/////////////////////////////////////////////////////////////////////////////



-(UIImage*)resizedImageToFitInSize:(CGSize)boundingSize scaleIfSmaller:(BOOL)scale
{
    // get the image size (independant of imageOrientation)
    CGImageRef imgRef = self.CGImage;
    CGSize srcSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef)); // not equivalent to self.size (which depends on the imageOrientation)!
    
    // adjust boundingSize to make it independant on imageOrientation too for farther computations
    UIImageOrientation orient = self.imageOrientation;
    switch (orient) {
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            boundingSize = CGSizeMake(boundingSize.height, boundingSize.width);
            break;
        default:
            // NOP
            break;
    }
    
    // Compute the target CGRect in order to keep aspect-ratio
    CGSize dstSize;
    
    if ( !scale && (srcSize.width < boundingSize.width) && (srcSize.height < boundingSize.height) ) {
        //NSLog(@"Image is smaller, and we asked not to scale it in this case (scaleIfSmaller:NO)");
        dstSize = srcSize; // no resize (we could directly return 'self' here, but we draw the image anyway to take image orientation into account)
    } else {		
        CGFloat wRatio = boundingSize.width / srcSize.width;
        CGFloat hRatio = boundingSize.height / srcSize.height;
        
        if (wRatio < hRatio) {
            //NSLog(@"Width imposed, Height scaled ; ratio = %f",wRatio);
            dstSize = CGSizeMake(boundingSize.width, floorf(srcSize.height * wRatio));
        } else {
            //NSLog(@"Height imposed, Width scaled ; ratio = %f",hRatio);
            dstSize = CGSizeMake(floorf(srcSize.width * hRatio), boundingSize.height);
        }
    }
    
    return [self resizedImageToSize:dstSize];
}

@end
